﻿using Domain.IRepositorys;
using Domain.Services;
using Domain.Types;
using Infrastructure.Job;
using Infrastructure.UniOfWorkBase;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using Utility;
using static Utility.PolicyUtil;

namespace Application.Job
{
    /// <summary>
    ///  任务达人，超级商人等级到期处理
    /// </summary>
    [Job("0 0 2 1/1 * ? ")]
    public class UserLevelOutTimeJob : AbstractJob
    {
        public IUserRepository userRepository { get; set; }
        public IEFUnitOfWork efUnitOfWork { get; set; }
        public ILogger<UserLevelOutTimeJob> Logger { get; set; }
        public override void Run()
        {
            var list = efUnitOfWork.Query<UloEntity>("SELECT Idx_UserLevelID uid,MAX(OutTime) outtime FROM levellog WHERE OutTime < Now() AND LogType='User' GROUP BY Idx_UserLevelID");
            
            foreach (var item in list)
            {
                try
                {
                    var u = userRepository.GetByKey(item.uid);
                    u.UserLevel = Domain.Types.UserLevel.普通用户;
                }
                catch (PolicyRetryException ex)
                {
                    Logger.LogException(ex, item);
                }
            }
            efUnitOfWork.Commit();
            efUnitOfWork.Reset();

            list = efUnitOfWork.Query<UloEntity>("SELECT Idx_UserLevelID uid,MAX(OutTime) outtime FROM levellog WHERE OutTime < Now() AND LogType='Trader' GROUP BY Idx_UserLevelID");

            foreach (var item in list)
            {
                try
                {
                    var u = userRepository.GetByKey(item.uid);
                    u.TraderLevel = TraderLevel.普通商家;
                }
                catch (PolicyRetryException ex)
                {
                    Logger.LogException(ex, item);
                }
            }
            efUnitOfWork.Commit();
        }

        public class UloEntity
        {
            public int uid { get; set; }
            public DateTime outtime { get; set; }
        }
    }
}
